package freedom.easyit.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.querydsl.core.types.Predicate;

import freedom.easyit.dao.ContactBookDao;
import freedom.easyit.dao.MailHistoryDao;
import freedom.easyit.domain.ContactBook;
import freedom.easyit.domain.MailHistory;
import freedom.easyit.domain.QContactBook;
import freedom.easyit.domain.QMailHistory;
import freedom.easyit.dto.ContactBookDto;
import freedom.easyit.enums.GenderEnum;
import freedom.easyit.enums.MailTypeEnum;
import freedom.easyit.service.MailService;

/**
 * @author Charlie Email:tingfangcao@163.com
 * @date 2020/10/20
 */
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private ContactBookDao contactBookDao;
    @Autowired
    private MailHistoryDao mailHistoryDao;
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void send() throws FileNotFoundException, MessagingException {
        // 获取通讯录中生日是今天的
        QContactBook qcb = QContactBook.contactBook;
        Predicate predicate = qcb.birthday.dayOfYear().eq(LocalDate.now().getDayOfYear());
        // 适应庞大通讯录情况
        Pageable pageRequest = PageRequest.of(0, 100);
        Page<ContactBook> page = contactBookDao.findAll(predicate, pageRequest);
        send(page.getContent());
        while (page.hasNext()) {
            pageRequest = PageRequest.of(0, 100);
            pageRequest = page.nextPageable();
            page = contactBookDao.findAll(predicate, pageRequest);
            send(page.getContent());
        }
    }

    @Override
    public void send(List<ContactBook> contactBookList) throws FileNotFoundException, MessagingException {
        this.send(contactBookList, false);
    }
    
    @Override
    public void send(List<ContactBook> contactBookList, boolean check) throws FileNotFoundException, MessagingException {
        for (ContactBook contactBook : contactBookList) {
            send(contactBook, check);
        }
    }

    static final String[] GREETING =
        {
            "花朝月夕，如诗如画；在这个真正属于你的日子里，愿你拥抱未来，愿你的容颜像春天般绚烂。生日快乐！", 
            "愿如梁上燕，岁岁常相见。生日快乐！", 
            "愿你成为自己的太阳，无需凭借谁的光芒；愿你所有的情深意重，都能换来岁月温柔；愿你一生努力，一生被爱。生日快乐！",
            "你加了一岁，加了一份魅力，加了一份成熟，加了一份智慧...生日快乐！"};

    @Override
    public void send(ContactBook contactBook) throws FileNotFoundException, MessagingException {
        this.send(contactBook, true);
    }
    
    AtomicInteger a = new AtomicInteger();
    AtomicInteger b = new AtomicInteger();

    public int inc(AtomicInteger a, int max) {
        if (a.compareAndSet(3, 0))
            ;
        return a.getAndIncrement();
    }

    public int ainc() {
        return inc(a, GREETING.length - 1);
    }

    public int binc() {
        return inc(b, BACKGROUND.length - 1);
    }
    
    @Override
    public void send(ContactBook contactBook, boolean check) throws FileNotFoundException, MessagingException {
        if(check) {
            // 阻止重复发送
            QMailHistory qmh = QMailHistory.mailHistory;
            Predicate predicate = qmh.sendTo.eq(contactBook.getEmail()).and(qmh.sendAt.eq(contactBook.getBirthday()))
                .and(qmh.mailType.eq(MailTypeEnum.BIRTHDAY_GREET));
            if (mailHistoryDao.exists(predicate)) {
                return;
            }
        }
        // 发送邮件
        DateFormatter dateFormatter = new DateFormatter("yyyy.MM.dd");
        // 随问候语
        int i = ainc();
        
        send(contactBook.getEmail(), "生日问候", GREETING[i], dateFormatter.print(contactBook.getBirthday(), Locale.getDefault()));
        // 记录发送历史
        mailHistoryDao
        .save(new MailHistory(contactBook.getEmail(), contactBook.getBirthday(), MailTypeEnum.BIRTHDAY_GREET));
        
    }

    /**
     * 用来发送模版邮件
     */
    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private MailProperties mailProperties;
    
    static final String SIGN = "static/image/sign1.png";
    static final String[] BACKGROUND =
    {
        "static/image/bg1.png", 
        "static/image/bg2.png", 
        "static/image/bg3.png", 
        };
    
    @Override
    public void send(String to, String subject, String content, String signDate) throws FileNotFoundException, MessagingException {

        Context context = new Context();
        context.setVariable("subject", subject);
        context.setVariable("content", content);
        context.setVariable("signDate", signDate);
        String emailContent = templateEngine.process("birthday-mail", context);

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(emailContent, true);
            // 随机背景
            int i = binc();
            File bg1 = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + BACKGROUND[i]);
//            File bg1 = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + BACKGROUND[2]);
            helper.addInline("bg1.png", bg1);
            File sign1 = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + SIGN);
            helper.addInline("sign1.png", sign1);
        mailSender.send(message);
    }

    @Override
    public void save(List<ContactBookDto> contactBookDtoList) {
        List<ContactBook> contactBookList = new ArrayList<>();
        for (ContactBookDto contactBookDto : contactBookDtoList) {
            ContactBook temp = new ContactBook();
            BeanUtils.copyProperties(contactBookDto, temp, ContactBookDto.PROP_GENDAR);
            temp.setGender(GenderEnum.fromString(contactBookDto.getGendar()));
            contactBookList.add(temp);
        }
        // TODO 尽量别直接调用多次insert, 使用batchInsert,所有数据一次性插入
        contactBookDao.saveAll(contactBookList);
    }

    @Override
    public List<ContactBook> listContactBook() {
         return contactBookDao.findAll();
    }

    @Override
    public List<MailHistory> listMailHistory10() {
        Pageable pr = PageRequest.of(0, 10, Direction.DESC, MailHistory.PROP_SEND_AT);
        return mailHistoryDao.findAll(pr).getContent();
    }
    
}
